package com.ctg.behavior.calc.controller;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.common.CtgResult;
import com.ctg.behavior.common.properties.CtPropertiesRequest;
import com.ctg.behavior.common.properties.CtPropertiesResult;
import com.ctg.behavior.common.properties.CtPropertyValuesCalcRequest;
import com.ctg.behavior.common.properties.CtPropertyValuesCalcResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/property")
public class CtPropertyController {

	@Value("${simulator.path}")
	private String simlutorPath;

	@PostMapping("/properties")
	public CtPropertiesResult properties(@RequestBody CtPropertiesRequest request) throws Exception {

		CtPropertiesResult result = new CtPropertiesResult();

		String type = request.getReq().getType();
		// 检查参数
		if (StringUtils.isEmpty(type)) {
			log.error("type={}", type);
			result.setErrorCode("400");
			result.setErrorMessage("type is null");
			result.setSuccess(false);
			return result;
		}
		String filePath = simlutorPath + "/property/properties/";
		FileUtils.forceMkdir(new File(filePath));

		if ("user".equalsIgnoreCase(type)) {
			String targetFilePath = filePath + type + ".json";
			File targetFile = new File(targetFilePath);
			if (!targetFile.exists()) {
				ClassPathResource classPathResource = new ClassPathResource("user.properties.json");
				InputStream inputStream = classPathResource.getInputStream();
				List<String> lines = IOUtils.readLines(inputStream, "UTF-8");
				StringBuilder sbuilder = new StringBuilder();
				for (String line : lines) {
					sbuilder.append(line);
				}
				result = JSON.parseObject(sbuilder.toString(), CtPropertiesResult.class);
			} else {
				String resultText = FileUtils.readFileToString(targetFile, "UTF-8");
				result = JSON.parseObject(resultText, CtPropertiesResult.class);
			}

			return result;
		}

		List<String> events = request.getReq().getEvents();
		if (events.isEmpty()) {
			log.error("type={}", type);
			log.error("events={}", events);
			result.setSuccess(false);
			return result;
		}

		if ("event".equalsIgnoreCase(type)) {
			String targetFilePath = filePath + type + ".json";
			File targetFile = new File(targetFilePath);
			if (!targetFile.exists()) {
				ClassPathResource classPathResource = null;
				if (String.valueOf(request.getReq().getEvents().get(0)).equals("_Anything")) {
					classPathResource = new ClassPathResource("event.properties_all.json");
				} else if (String.valueOf(request.getReq().getEvents().get(0)).equals("_AppClick")) {
					classPathResource = new ClassPathResource("event.properties_appclick.json");
				} else {
					classPathResource = new ClassPathResource("event.properties.json");
				}
				InputStream inputStream = classPathResource.getInputStream();
				List<String> lines = IOUtils.readLines(inputStream, "UTF-8");
				StringBuilder sbuilder = new StringBuilder();
				for (String line : lines) {
					sbuilder.append(line);
				}
				result = JSON.parseObject(sbuilder.toString(), CtPropertiesResult.class);
			} else {
				String resultText = FileUtils.readFileToString(targetFile, "UTF-8");
				result = JSON.parseObject(resultText, CtPropertiesResult.class);
			}

			return result;
		}

		return result;
	}

	@PostMapping("/propertiesTMU")
	public CtgResult propertiesTMU(@RequestBody CtPropertiesResult tmResult, @RequestParam("type") String type) throws Exception {

		CtgResult result = new CtgResult();
		log.info("type={}", type);

		// 检查参数
		if (StringUtils.isEmpty(type)) {
			log.error("type={}", type);
			result.setErrorMessage("param type is null");
			result.setSuccess(false);
			return result;
		}
		String filePath = simlutorPath + "/property/properties/" + type;
		FileUtils.forceMkdir(new File(filePath));

		if ("user".equalsIgnoreCase(type)) {

			String targetFilePath = filePath + ".json";
			File targetFile = new File(targetFilePath);

			FileUtils.writeStringToFile(targetFile, JSON.toJSONString(tmResult), "UTF-8");

			return result;
		} else if ("event".equalsIgnoreCase(type)) {

			String targetFilePath = filePath + ".json";
			File targetFile = new File(targetFilePath);

			FileUtils.writeStringToFile(targetFile, JSON.toJSONString(tmResult), "UTF-8");

			return result;
		}

		result.setSuccess(false);

		return result;
	}

	@PostMapping("/values")
	public CtPropertyValuesCalcResult values(@RequestBody CtPropertyValuesCalcRequest request) throws Exception {

		CtPropertyValuesCalcResult result = new CtPropertyValuesCalcResult();

		String field = request.getReq().getField();
		// 检查参数
		if (StringUtils.isEmpty(field)) {
			log.error("field={}", field);
			result.setSuccess(false);
			return result;
		}

		// CtCalcPropertyType propertyType = CtCalcPropertyUtils.getValueType(field);

		String filePath = simlutorPath + "/property/values";
		FileUtils.forceMkdir(new File(filePath));
		String targetFilePath = filePath + "/" + field + ".json";
		File targetFile = new File(targetFilePath);
		if (!targetFile.exists()) {
			if (field.endsWith("lib")) {
				result.getValue().getList().add("iOS");
				result.getValue().getList().add("Android");
				result.getValue().getList().add("js");
				result.getValue().getList().add("python");
			}
			return result;
		}

		String resultText = FileUtils.readFileToString(targetFile, "UTF-8");
		result = JSON.parseObject(resultText, CtPropertyValuesCalcResult.class);

		if (!StringUtils.isEmpty(request.getReq().getFuzzyStr())) {
			List<String> returnRows = new ArrayList<>();
			List<String> tempRows = result.getValue().getList();
			for (Object oneRow : tempRows) {
				String tempStr = String.valueOf(oneRow);
				if (tempStr.indexOf(request.getReq().getFuzzyStr()) >= 0) {
					returnRows.add(tempStr);
				}
			}
			result.getValue().setList(returnRows);
		}

		return result;
	}

	@PostMapping("/valuesTMU")
	public CtgResult eventsAllTMU(@RequestBody CtPropertyValuesCalcResult tmResult, @RequestParam("field") String field) throws Exception {

		CtgResult result = new CtgResult();
		log.info("field={}", field);
		if (StringUtils.isEmpty(field)) {
			result.setErrorMessage("field is null");
			result.setSuccess(false);
			return result;
		}

		String filePath = simlutorPath + "/property/values";
		FileUtils.forceMkdir(new File(filePath));
		String targetFilePath = filePath + "/" + field + ".json";
		File targetFile = new File(targetFilePath);

		FileUtils.writeStringToFile(targetFile, JSON.toJSONString(tmResult), "UTF-8");

		return result;
	}

}
